package com.go.where.family.api.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.go.where.family.api.constants.Constant;
import com.go.where.family.api.server.HttpServerStartMain;
import com.go.where.family.api.utils.CommonUtil;
import com.go.where.family.api.utils.DateUtil;
import com.go.where.family.api.utils.ServletUtil;
import com.go.where.family.api.vo.ResultVo;
import com.google.gson.Gson;

/**
 * 上传图片
 * 
 * @description
 * @author
 * @date
 */
public class UploadImageServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(UploadImageServlet.class);
	private static Gson gson = CommonUtil.gson();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);
		try {
			String loadpath = HttpServerStartMain.getValue("photo.location")
					+ Constant.UPLOAD_IMAGE_PATH; // 上传文件存放目录
			String temp = loadpath; // 临时目录
			File file = new File(loadpath);
			if (!file.exists()) {
				file.mkdirs();
			}

			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024 * 1024);
			factory.setRepository(new File(temp)); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 开始读取上传信息
			List<FileItem> fileItems = upload.parseRequest(req);
			StringBuffer sBuffer = new StringBuffer();

			if (fileItems != null && fileItems.size() > 0) {
				FileItem item = fileItems.get(0);// 忽略其他不是文件域的所有表单信息
				if (!item.isFormField()) {
					String name = item.getName();// 获取上传文件名,包括路径
					name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
					long size = item.getSize();
					if ((name == null || name.equals("")) && size == 0) {
						ServletUtil.writeErrorStr(resp);
						return;
					}
					name = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "_"
							+ CommonUtil.createRandomNumber() + ".jpg";
					File fNew = new File(loadpath, name);
					item.write(fNew);
					sBuffer.append(Constant.UPLOAD_IMAGE_PATH + name);
				}
			}
			// Iterator<FileItem> iter = fileItems.iterator(); // 依次处理每个上传的文件
			// while (iter.hasNext()) {
			// FileItem item = iter.next();// 忽略其他不是文件域的所有表单信息
			// if (!item.isFormField()) {
			// String name = item.getName();// 获取上传文件名,包括路径
			// name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
			// long size = item.getSize();
			// if ((name == null || name.equals("")) && size == 0)
			// continue;
			// name = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "_"
			// + index + "_" + CommonUtil.createRandomNumber()
			// + ".jpg";
			// index++;
			// File fNew = new File(loadpath, name);
			// item.write(fNew);
			// sBuffer.append(Constant.UPLOAD_IMAGE_PATH + name);
			// }
			// else// 取出不是文件域的所有表单信息
			// {
			// String fieldvalue = item.getString();
			// 如果包含中文应写为：(转为UTF-8编码)
			// String fieldvalue = new
			// String(item.getString().getBytes(),"UTF-8");
			// }
			// }
			ResultVo ri = new ResultVo();
			ri.setCode(Constant.SUCCESS);
			ri.setStatus(Constant.TRUE);
			ri.setData(sBuffer.toString());
			ServletUtil.writeResJsonStr(resp, gson.toJson(ri));

		} catch (Exception e) {
			log.error("解析图片流异常", e);
			ServletUtil.writeErrorStr(resp);
		}
	}

}
